<div class="layui-fluid">
    <div class="layui-row">
        <div class="layui-col-xs12">
            <div class="layui-card">
                <div class="layui-card-body">
                    <div class="layui-card-header">
                        <div class="layui-row" id="title-label">
                        </div>
                    </div>

                    <div class="layui-card-body">
                        <form class="layui-form" action="" accept-charset="UTF-8" method="post" id="base_form" lay-filter="base_form">
                            <input id="at_id" type="hidden" name="id">
                            <div class="layui-row">
                                <div class="layui-col-md6">
                                    <div class="layui-form-item">
                                        <label class="layui-form-label">标题</label>
                                        <div class="layui-input-block">
                                            <input type="text" name="title" required lay-verify="required" placeholder="不超过50个字" maxlength="50" autocomplete="off" class="layui-input">
                                        </div>
                                    </div>
                                </div>
                                <!-- <div class="layui-col-md6">
                                    <div class="layui-form-item">
                                        <label class="layui-form-label">类别</label>

                                        <div class="layui-input-block">
                                            <select name="ntId" lay-filter="showType" id="showType">
												<option value="" selected="">未选择</option>
											</select>
                                        </div>
                                    </div>
                                </div> -->
                            </div>

                            <div class="layui-row">
                                <div class="layui-col-md6">
                                    <div class="layui-form-item">
                                        <label class="layui-form-label">封面</label>
                                        <div class="layui-upload">
                                            <button type="button" class="layui-btn layui-btn-normal" id="test1_hash">上传图片</button>
                                            <!-- <div class="layui-upload-list">
								              <img class="layui-upload-img" id="demo1_hash" style="width:10%;margin-left:10%">
								              <p id="demoText_hash"></p>
								          </div> -->
                                        </div>
                                    </div>
                                    <div class="layui-form-item">
                                        <div class="layui-input-block">
                                            <img class="layui-upload-img" id="demo1_hash" style="width:10%">
                                        </div>
                                    </div>
                                </div>
                                <div class="layui-col-md6">
                                    <div class="layui-form-item">
                                        <label class="layui-form-label">附件名称</label>
                                        <div class="layui-input-block">
                                            <input type="text" name="fileName" placeholder="名称不能包含特殊字符,只允许子母,数字,汉字;不填附件名称将不会保存附件" autocomplete="off" class="layui-input" maxlength="50">
                                        </div>
                                    </div>
                                    <div class="layui-form-item">
                                        <label class="layui-form-label">附件</label>
                                        <div class="layui-upload">
                                            <button type="button" class="layui-btn layui-btn-normal" id="test2_hash">上传文件</button>
                                            <label class="layui-form-label yishanchuan" id="file_upload_success"></label>
                                            <button type="button" class="layui-btn layui-btn-danger del_file">删除</button>
                                            <input type="hidden" name="file_del">
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div class="layui-form-item">
                                <label class="layui-form-label">摘要</label>
                                <div class="layui-input-block">
                                    <input type="text" name="summary" required lay-verify="required" placeholder="不超过100个字" autocomplete="off" class="layui-input" maxlength="100">
                                </div>
                            </div>

                            <div class="layui-form-item">
                                <label class="layui-form-label">新闻内容</label>
                                <div class="layui-input-block">
                                    <textarea id="content_edit" name="content" style="display: none;"></textarea>
                                </div>
                            </div>
							
							<div class="layui-form-item">
							    <label class="layui-form-label">优先级</label>
							    <div class="layui-input-block">
							        <input type="number" name="sort" placeholder="输入数字,数字越大,显示越靠前" maxlength="8"
							               autocomplete="off" class="layui-input" onkeyup="this.value=this.value.replace('.','')"
											onafterpaste="this.value=this.value.replace('.','')">
							    </div>
							</div>

                            <div class="layui-form-item">
                                <label class="layui-form-label">发布状态</label>

                                <div class="layui-input-block">
                                    <select name="state">
										<option value="0">草稿</option>
										<option value="1" selected="">发布</option>
									</select>
                                </div>
                            </div>

                            <div class="layui-form-item">
                                <div class="layui-input-block">
                                    <button class="layui-btn layui-btn-normal" lay-submit="" lay-filter="save">保存</button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    layui.config({
        base: '/src/js/'
    }).use(['admin', 'jquery', 'mockjs', 'table', 'sidebar', 'form', 'upload', "layedit"], function() {
        var $ = layui.jquery,
            admin = layui.admin,
            layer = layui.layer,
            table = layui.table,
            sidebar = layui.sidebar,
            form = layui.form,
            upload = layui.upload;
        var layedit = layui.layedit;
        var isAdd = true;
        var id = getUrlParam("id");
        var imgUrl;
        var fileUrl;


        httpPost_async(GET_NEWSTYPE_LIST, {
            pageSize: 100000,
            pageNum: 1
        }, function(results) {
            for (var i = 0; i < results.list.length; i++) {
                $("#showType").append("<option value='" + results.list[i].id + "'>" + results.list[i].typeName + "</option>");
            }
        }, function(message) {

        });

        form.render();
        if (id != undefined && id != "") {
            $("#title-label").text('修改新闻');
            $("#at_id").val(id);
            isAdd = false;
            var index = layer.load(2);
            httpPost(GET_NEWS_INFO, {
                id: id
            }, function(results) {
                layer.close(index);
                form.val("base_form", {
                    "title": results.title,
                    "summary": results.summary,
                    "state": results.state,
                    "fileName": results.fileName,
                    "ntId": results.newsType ? results.newsType.id : "",
					"sort": results.sort
                });
                imgUrl = results.img;
                $('#demo1_hash').attr('src', results.img);
                layedit.setContent(content_edit, results.content);
                if (!isObjNull(results.fileName)) {
                    fileUrl = results.fileUrl;
                    $('#file_upload_success').text("已上传");
                }
                if (isObjNull(results.fileUrl)) {
                    fileUrl = results.fileUrl;
                    $('#file_upload_success').text("");
                }
            }, function(message) {
                layer.close(index);
            });
        } else {
            $("#title-label").text('新增新闻');
        }

        form.on('submit(save)', function(data) {
            // layer.msg("保存成功");
            var url;
            if (isAdd) {
                url = ADD_NEWS;
            } else {
                url = UPDATE_NEWS;
            }
            var params = data.field;
            params.img = imgUrl;
            params.fileUrl = fileUrl;
            params.content = layedit.getContent(content_edit);

//             if (isObjNull(params.ntId)) {
//                 layer.msg("请先选择新闻分类");
//                 return false;
//             }
            if (params.title.length > 50) {
                layer.msg('标题不能超过50个字');
                return false;
            }
			if(isObjNull(imgUrl)){
				layer.msg("请先设置封面图片");
				return false;
			}
            if (params.summary.length > 100) {
                layer.msg('副标题不能超过100个字');
                return false;
            }
            if (isObjNull(params.content)) {
                layer.msg("请先填写新闻内容");
                return false;
            }

            if (params.fileName.length > 0 && isObjNull(params.fileUrl)) {
                layer.msg("您已填写了附件名称，请先上传附件");
                return false;
            }
            if (!params.fileName.length && params.fileUrl) {
                layer.msg("您已上传了附件，请填写附件名称");
                return false;
            }
			
			if(params.sort && params.sort.length > 5){
				layer.msg('优先级过大');
				return false;
			}
            var index = layer.load(2);
            httpPost(url, params, function(results) {
                if (isObjNull(id)) {
                    parent.layer.msg("添加成功");
                    window.history.go(-1);
                    // window.location.href="javascript:history.go(-1)";
                } else {
                    parent.layer.msg("修改成功");
                }
                layer.close(index);
            }, function(message) {
                parent.layer.msg(message);
                layer.close(index);
            });

            return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
        });

        form.on('select(showType)', function(data) {
            if (data.value == 1) {
                $("#url-div").show();
            } else {
                $("#url-div").hide();
            }
        });

        //普通图片上传
        var uploadInst = upload.render({
            elem: '#test1_hash',
            url: UPLOAD_IMAGE + "?width=800",
            before: function(obj) {
                //预读本地文件示例，不支持ie8
                obj.preview(function(index, file, result) {
                    $('#demo1_hash').attr('src', result); //图片链接（base64）
                });
            },
            done: function(res) {
                //如果上传失败
                if (res.status > 0) {
                    return layer.msg('上传失败');
                }

                //上传成功
                imgUrl = res.data.src;

            },
            exts: 'jpg|png|jpeg',
            error: function() {
                //演示失败状态，并实现重传
                var demoText = $('#demoText_hash');
                demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-mini demo-reload">重试</a>');
                demoText.find('.demo-reload').on('click', function() {
                    uploadInst.upload();
                });
            }
        });




        //文件上传
        var uploadInst = upload.render({
            elem: '#test2_hash',
            url: UPLOAD_IMAGE,
            before: function(obj) {
                //预读本地文件示例，不支持ie8
                obj.preview(function(index, file, result) {
                    $('#file_upload_success').text("正在上传"); //图片链接（base64）
                });
            },
            accept: 'file',
            done: function(res) {
                //如果上传失败
                if (res.status > 0) {
                    $('#file_upload_success').text("上传失败"); //图片链接（base64）
                    return layer.msg('上传失败');
                }
                $('#file_upload_success').text("已上传"); //图片链接（base64）
                //上传成功
                fileUrl = res.data.src;


            },
            error: function() {
                //演示失败状态，并实现重传
                var demoText = $('#demoText_hash');
                demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-mini demo-reload">重试</a>');
                demoText.find('.demo-reload').on('click', function() {
                    uploadInst.upload();
                });
            }
        });
        $(document).on("click", ".del_file", function() {
            $("[name=file_del]").val("0");
            if ($("[name=file_del]").val() == "0") {
                $("[name=fileName]").val("");
                $(".yishanchuan").text("");
                fileUrl = "";

            }
        });

        layedit.set({
            //暴露layupload参数设置接口 --详细查看layupload参数说明
            uploadImage: {
                url: UPLOAD_IMAGE,
                accept: 'image',
                acceptMime: 'image/*',
                exts: 'jpg|png|bmp|jpeg',
                size: 1024 * 10,
                done: function(data) {
                    console.log(data);
                }
            }
            //开发者模式 --默认为false
            ,
            devmode: true
                //插入代码设置 --hide:true 等同于不配置codeConfig
                ,
            codeConfig: {
                hide: false, //是否显示编码语言选择框
                default: 'javascript' //hide为true时的默认语言格式
            }
            //新增iframe外置样式和js
            //, quote:{
            //    style: ['/Content/Layui-KnifeZ/css/layui.css','/others'],
            //    js: ['/Content/Layui-KnifeZ/lay/modules/jquery.js']
            //}
            //自定义样式-暂只支持video添加
            //, customTheme: {
            //    video: {
            //        title: ['原版', 'custom_1', 'custom_2']
            //        , content: ['', 'theme1', 'theme2']
            //        , preview: ['', '/images/prive.jpg', '/images/prive2.jpg']
            //    }
            //}
            //插入自定义链接
            ,
            customlink: {
                title: '插入layui官网',
                href: 'https://www.layui.com',
                onmouseup: ''
            },
            facePath: 'http://knifez.gitee.io/kz.layedit/Content/Layui-KnifeZ/',
            devmode: true,
            videoAttr: ' preload="none" ',
            tool: ['undo', 'redo', 'code', 'strong', 'italic', 'underline', 'del', '|', 'fontFomatt', 'fontfamily', 'fontSize', 'fontBackColor', 'colorpicker', '|', 'left', 'center', 'right', '|', 'image_alt', '|', 'table', 'customlink'],
            height: '500px'
        });
        var content_edit = layedit.build("content_edit");





    });
</script>

<style scoped>

</style>